package com.thinkfit.jy.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.CollectionUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.activity.BaseActivity;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.mvp.contract.EmptyContract;
import com.common.lib.mvp.presenter.EmptyPresenter;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.DialogActivity;
import com.thinkfit.jy.activity.SettingNewActivity;
import com.thinkfit.jy.activity.SettingNewOtherActivity;
import com.thinkfit.jy.adapter.WifiAdapter;
import com.thinkfit.jy.bean.WifiBean;
import com.thinkfit.jy.bean.WifiConnectState;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.WifiSupport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * wifi列表界面
 */
public class WifiConnectFragment extends BaseFragment<EmptyContract.Presenter> implements EmptyContract.View {
    List<WifiBean> mWifiList = new ArrayList<>();
    private int mConnectType = 0;//1：连接成功？ 2 正在连接（如果wifi热点列表发生变需要该字段）
    private WifiAdapter mAdapter;
    private RecyclerView recyclerView;
    private boolean isExit = false;
    private boolean mWasAssociated;
    private boolean mWasAssociating;
    private boolean mWasHandshaking;
    private boolean isWifiChange = false;

    private WifiBean mConnectionWifi;

    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private WifiManager mWifiManager;

    private ActivityResultLauncher mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Intent data = result.getData();
                int type = data.getIntExtra(Constants.BUNDLE_EXTRA, 0);
                switch (type) {
                    case DialogActivity.SHOW_WIFI_DISCONNECT_DIALOG:
                        WifiInfo wifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                        if (wifiInfo != null) {
                            WifiSupport.doDisconnectWifi(wifiInfo.getSSID(), getActivity());
                        }
                        mConnectType = 0;
                        mConnectionWifi = null;
                        sortScaResult();
                        ((SettingNewOtherActivity) getActivity()).setWifiImag(false);
//                        ((SettingNewActivity) getActivity()).setWifiImag(false);
                        break;
                    case DialogActivity.SHOW_INPUT_WIFI_PSW_DIALOG:
                        String psw = data.getStringExtra(Constants.BUNDLE_EXTRA_2);
                        wifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                        if (wifiInfo != null) {
                            WifiSupport.doDisconnectWifi(wifiInfo.getSSID(), getActivity());
                        }
                        WifiConfiguration wifiConfiguration = WifiSupport.createWifiConfig(mConnectionWifi.getWifiName(), psw,
                                WifiSupport.getWifiCipher(mConnectionWifi.getCapabilities()));
                        if (WifiSupport.addNetWork(wifiConfiguration, getActivity())){
                            ((SettingNewOtherActivity) getActivity()).setWifiImag(true);
//                            ((SettingNewActivity) getActivity()).setWifiImag(true);
                            if (recyclerView!=null && mAdapter != null)
                                recyclerView.scrollToPosition(0);
                        };
                        showProgressDialog();
                        break;
                }

            }
        }
    });

    @NonNull
    @Override
    protected EmptyContract.Presenter onCreatePresenter() {
        return new EmptyPresenter(this);
    }

    @Override
    protected int getLayoutId() {
//        return DataManager.Companion.getInstance().getMainStyle() == 3 ? R.layout.fragment_wifi_connect_xm : R.layout.fragment_wifi_connect;
        return R.layout.fragment_wifi_connect;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        setViewsOnClickListener(R.id.tvBack);

        recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        getAdapter().onAttachedToRecyclerView(recyclerView);
        recyclerView.setAdapter(getAdapter());

        sortScaResult();
    }


    private WifiAdapter getAdapter() {
        if (mAdapter == null) {
            mAdapter = new WifiAdapter(getActivity());
            mAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    mConnectionWifi = mAdapter.getItem(position);
                    WifiConnectState state = mConnectionWifi.getState();
                    if (state == WifiConnectState.UnConnected) {
                        WifiSupport.WifiCipherType wifiCipher = WifiSupport.getWifiCipher(mConnectionWifi.getCapabilities());
                        WifiConfiguration tempConfig = WifiSupport.isExsits(mConnectionWifi.getWifiName(), getActivity());
                        if (wifiCipher == WifiSupport.WifiCipherType.WIFICIPHER_NOPASS) {//无需密码
                            if (mConnectType != 0) {
                                WifiInfo wifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                                WifiSupport.doDisconnectWifi(wifiInfo.getSSID(), getActivity());
                                mConnectType = 0;
                            }
                            if (tempConfig == null) {
                                WifiConfiguration exist = WifiSupport.createWifiConfig(mConnectionWifi.getWifiName(), null, WifiSupport.WifiCipherType.WIFICIPHER_NOPASS);
                                if (WifiSupport.addNetWork(tempConfig, getActivity())){
                                    ((SettingNewOtherActivity) getActivity()).setWifiImag(true);
//                                    ((SettingNewActivity) getActivity()).setWifiImag(true);
                                    if (recyclerView!=null && mAdapter != null)
                                        recyclerView.scrollToPosition(0);
                                };
                            } else {
                                isExit = true;
                                if (WifiSupport.addNetWork(tempConfig, getActivity())){
                                    ((SettingNewOtherActivity) getActivity()).setWifiImag(true);
//                                    ((SettingNewActivity) getActivity()).setWifiImag(true);
                                    if (recyclerView!=null && mAdapter != null)
                                        recyclerView.scrollToPosition(0);
                                };
                            }
                        } else {
                            if (tempConfig == null) {
                                Intent intent = new Intent(getActivity(), DialogActivity.class);
                                intent.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.SHOW_INPUT_WIFI_PSW_DIALOG);
                                intent.putExtra(Constants.BUNDLE_EXTRA_2, mConnectionWifi.getWifiName());
                                mLauncher.launch(intent);
                            } else {
                                showProgressDialog();
                                if (mConnectType != 0) {
                                    WifiInfo wifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                                    WifiSupport.doDisconnectWifi(wifiInfo.getSSID(), getActivity());
                                    mConnectType = 0;
                                }
                                isExit = true;
                                WifiSupport.addNetWork(tempConfig, getActivity());
                            }
                        }
                    } else {
                        Intent intent = new Intent(getActivity(), DialogActivity.class);
                        intent.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.SHOW_WIFI_DISCONNECT_DIALOG);
                        mLauncher.launch(intent);
                    }
                }
            });
        }
        return mAdapter;
    }

//    private void showInputWifiPswDialog(WifiBean bean) {
//        final MyDialogFragment myDialogFragment = new MyDialogFragment(R.layout.activity_input_wifi_dialog);
//        myDialogFragment.setOnMyDialogListener(new MyDialogFragment.OnMyDialogListener() {
//            @Override
//            public void initView(@Nullable View view) {
//                ((TextView) view.findViewById(R.id.tv1)).setText(getString(R.string.app_input_xxx_wifi_psw, bean.getWifiName()));
//                myDialogFragment.setDialogViewsOnClickListener(view, R.id.btn1, R.id.btn2);
//            }
//
//            @Override
//            public void onViewClick(int viewId) {
//                switch (viewId) {
//                    case R.id.btn2:
//                        WifiInfo wifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
//                        if (wifiInfo != null) {
//                            WifiSupport.doDisconnectWifi(wifiInfo.getSSID(), getActivity());
//                        }
//                        String psw = ((TextView) myDialogFragment.getView().findViewById(R.id.etPsw)).getText().toString();
//                        WifiConfiguration wifiConfiguration = WifiSupport.createWifiConfig(bean.getWifiName(), psw, WifiSupport.getWifiCipher(bean.getCapabilities()));
//                        WifiSupport.addNetWork(wifiConfiguration, getActivity());
//                        showProgressDialog();
//                        break;
//                }
//            }
//        });
//        myDialogFragment.show(getChildFragmentManager(), "MyDialogFragment");
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvBack:
                getParentFragmentManager().popBackStack();
                break;
        }
    }

    private BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {

                // 扫描完成，处理扫描结果
                @SuppressLint("MissingPermission") List<ScanResult> scanResults = mWifiManager.getScanResults();
                scanResults = WifiSupport.noSameName(scanResults);
                ((BaseActivity) getActivity()).dismissProgressDialog();
                mWifiList.clear();
                if (!CollectionUtils.isEmpty(scanResults)) {
                    for (int i = 0; i < scanResults.size(); i++) {
                        if (!scanResults.get(i).SSID.equals("")) {
                            WifiBean wifiBean = new WifiBean();
                            wifiBean.setWifiName(scanResults.get(i).SSID);
                            wifiBean.setState(WifiConnectState.UnConnected);   //只要获取都假设设置成未连接，真正的状态都通过广播来确定
                            wifiBean.setCapabilities(scanResults.get(i).capabilities);
                            wifiBean.setLevel(WifiSupport.getLevel(scanResults.get(i).level) + "");
                            mWifiList.add(wifiBean);
                        }
                    }
                }
                //排序
                Collections.sort(mWifiList);
                getAdapter().setNewInstance(mWifiList);
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                if (connectedWifiInfo != null) {
                    mConnectType = 1;
                    wifiListSet(connectedWifiInfo.getSSID(), mConnectType);
                }
                getAdapter().notifyDataSetChanged();
                // 取消注册广播接收器（可选，如果只需要接收一次扫描结果的话）
                getActivity().unregisterReceiver(wifiScanReceiver);
            }
        }
    };

    public void sortScaResult() {
        mWifiManager = ((WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE));

        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        } else {

            // 注册广播接收器来监听扫描完成事件
            IntentFilter filter = new IntentFilter();
            filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
            getActivity().registerReceiver(wifiScanReceiver, filter);
            if (!mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(true);
            }
            mWifiManager.startScan();
            ((BaseActivity) getActivity()).showProgressDialog();
        }
    }

    /**
     * 将"已连接"或者"正在连接"的wifi热点放置在第一个位置
     *
     * @param wifiName
     * @param type
     */
    public void wifiListSet(String wifiName, int type) {
        int index = -1;
        WifiBean wifiInfo = new WifiBean();
        if (CollectionUtils.isEmpty(mWifiList)) {
            return;
        }
        for (int i = 0; i < mWifiList.size(); i++) {
            mWifiList.get(i).setState(WifiConnectState.UnConnected);
        }
        Collections.sort(mWifiList);//根据信号强度排序
        for (int i = 0; i < mWifiList.size(); i++) {
            WifiBean wifiBean = mWifiList.get(i);
            if (index == -1 && ("\"" + wifiBean.getWifiName() + "\"").equals(wifiName)) {
                index = i;
                wifiInfo.setLevel(wifiBean.getLevel());
                wifiInfo.setWifiName(wifiBean.getWifiName());
                wifiInfo.setCapabilities(wifiBean.getCapabilities());
                wifiInfo.setState(type == 0 ? WifiConnectState.UnConnected
                        : (type == 1 ? WifiConnectState.Connected : WifiConnectState.Connecting));
            }
        }
        if (index != -1) {
            mWifiList.remove(index);
            mWifiList.add(0, wifiInfo);
            getAdapter().setNewInstance(mWifiList);
        }
        getAdapter().notifyDataSetChanged();
    }


    @Override
    public void onStop() {
        super.onStop();
        System.out.println("ddddddddddddddddddddddd   WifiConnectFragment ");
        DeviceTypeUtils.showBackButton(getContext().getApplicationContext());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBroadcastReceive(Intent intent) {
        if (getView() == null) {
            return;
        }
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (state) {
                case WifiManager.WIFI_STATE_DISABLED: {
                    Log.d(TAG, "已经关闭");
                    break;
                }
                case WifiManager.WIFI_STATE_DISABLING: {
                    Log.d(TAG, "正在关闭");
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLED: {
                    Log.d(TAG, "已经打开");
                    sortScaResult();
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLING: {
                    Log.d(TAG, "正在打开");
                    break;
                }
                case WifiManager.WIFI_STATE_UNKNOWN: {
                    Log.d(TAG, "未知状态");
                    break;
                }
            }
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
                Log.d(TAG, "wifi没连接上");
                for (int i = 0; i < mWifiList.size(); i++) {//没连接上将 所有的连接状态都置为“未连接”
                    mWifiList.get(i).setState(WifiConnectState.UnConnected);
                }
            } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                Log.d(TAG, "wifi连接上了");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                //连接成功 跳转界面 传递ip地址
                mConnectType = 1;
                wifiListSet(connectedWifiInfo.getSSID(), mConnectType);
                dismissProgressDialog();
                HashMap<String, Object> map = new HashMap<>();
                map.put(EventBusEvent.BLUETOOTH_CHANGE, false);
                EventBus.getDefault().post(map);
                ((SettingNewOtherActivity) getActivity()).setWifiImag(true);
//                ((SettingNewActivity) getActivity()).setWifiImag(true);
                if (recyclerView!=null && mAdapter != null)
                    recyclerView.scrollToPosition(0);
            } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                Log.d(TAG, "wifi正在连接");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                mConnectType = 2;
                wifiListSet(connectedWifiInfo.getSSID(), mConnectType);
            }
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
            isWifiChange = true;
        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            switch (state) {//TODO Setting文件里面代码，网络状态监听变化 断开、连接、密码错误的操作全在这里进行
                case ASSOCIATING://申请连接中
                    mWasAssociating = true;
                    break;
                case ASSOCIATED:
                    mWasAssociated = true;
                    break;
                case COMPLETED://连接成功后进入
                    isExit = false;
                    dismissProgressDialog();
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(EventBusEvent.REFRESH_WIFI, 0);
                    EventBus.getDefault().post(map);
                    break;
                case DISCONNECTED://断开连接后进入dormant判断是密码错误还是其他连接错误
                case DORMANT:
                    if (mWasAssociated || mWasHandshaking) {
                        if (mConnectType != 0) {
                            //解绑
                            mConnectType = 0;
                            WifiSupport.doDisconnectWifi("\"" + mConnectionWifi.getWifiName() + "\"", getActivity());
                            sortScaResult();
                            dismissProgressDialog();
                            Intent i = new Intent(getActivity(), DialogActivity.class);
                            i.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.SHOW_INPUT_WIFI_PSW_DIALOG);
                            i.putExtra(Constants.BUNDLE_EXTRA_2, mConnectionWifi.getWifiName());
                            mLauncher.launch(i);
                            showToast(R.string.app_check_wifi_password);
                            ((SettingNewOtherActivity) getActivity()).setWifiImag(false);
//                            ((SettingNewActivity) getActivity()).setWifiImag(false);
                        }
                    }
                    break;
                case INTERFACE_DISABLED:
                case UNINITIALIZED:
                    break;
                case FOUR_WAY_HANDSHAKE://四次握手进入连接
                case GROUP_HANDSHAKE:
                    mWasHandshaking = true;
                    break;
            }
        }
    }

}
